<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use App\Console\Commands\WdtClient;

// 物流同步回写定时任务 5min一次
//接口描述：将物流同步（发货状态、物流单号等）是否成功的结果批量回传给旺店通ERP。
//文档地址: https://open.wangdian.cn/qyb/open/apidoc/doc?path=logistics_sync_ack.php
// 执行命令: php artisan sync:LogisticsSyncAck
class LogisticsSyncAck extends Command
{
    protected $signature = 'sync:LogisticsSyncAck';
    protected $description = '将物流同步状态批量回写到旺店通';

    public function handle()
    {
        Log::info('LogisticsSyncAck', ['开始物流同步回写']);
        $sid = config('services.wdt.sid');
        $appKey = config('services.wdt.appkey');
        $secret = config('services.wdt.secret');
        $url = config('services.wdt.url') . 'logistics_sync_ack.php';
        $c = new WdtClient($sid, $appKey, $secret, $url);
        $limit = 100;
        $this->syncAck($c, $limit);
        $this->info('LogisticsSyncAck任务执行完毕');
    }

    /**
     * 分批回写物流同步状态
     */
    private function syncAck($client, $limit)
    {
        do {
            // 查询待回写的订单
            $orders = DB::table('store_order')
                ->whereNotNull('rec_id') //logistics_sync_ack回写状态
                ->where('rec_id', '!=', '') // rec_id不为空
                ->where('order_status', 2)
                ->where('send_status', 1)
                ->limit($limit)
                ->get();
            if ($orders->isEmpty()) {
                break;
            }
            $logisticsList = [];
            foreach ($orders as $order) {
                if (empty($order->rec_id)) {
                    continue; // rec_id不存在或为空则跳过
                }
                $logisticsList[] = [
                    'rec_id' => $order->rec_id,
                    'status' => 0, // 0成功
                    'message' => '',
                ];
            }
            $requestParams = [
                'logistics_list' => $logisticsList,
            ];
            Log::info('LogisticsSyncAck 请求参数', $requestParams);
            $client->putApiParam('logistics_list', json_encode($logisticsList, JSON_UNESCAPED_UNICODE));
            $result = $client->wdtOpenApi();
            $resultArr = json_decode($result, true);
            Log::info('LogisticsSyncAck result', [$resultArr]);
            if (!isset($resultArr['code']) || $resultArr['code'] != 0) {
                Log::error('LogisticsSyncAck error', [$resultArr]);
                break;
            }

            // 标记已同步或非待同步的订单
            if (isset($resultArr['errors']) && is_array($resultArr['errors'])) {
                foreach ($resultArr['errors'] as $error) {
                    if (isset($error['rec_id'])) {
                        // 标记本地订单，避免下次再同步
                        Log::info('LogisticsSyncAck error 参数', $error);
                        break;
//                        DB::table('store_order')->where('rec_id', $error['rec_id'])->update(['send_status' => 2]);
                    }
                }
            } else {
                // 全部成功，批量标记 发货状态 1:待发货 2：已发货 3：已收货
                foreach ($logisticsList as $item) {
                    DB::table('store_order')->where('rec_id', $item['rec_id'])->update(['send_status' => 2]);
                }
            }
        } while (true);
    }
} 